/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.biz;

import com.myapp.beans.Helper;
import com.myapp.entities.Question;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.NodeIterator;

/**
 *
 * @author Vinh_Dragon
 */
public class QuestionBiz {
    /**
     * 
     * @param realPath
     * @return
     */
    public ArrayList<Question> getListQuestion(String realPath) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            DocumentBuilder builder = factory.newDocumentBuilder();

            //realPath = getServlet().getServletContext().getRealPath("/");
            String path = realPath + "questions.xml";
            Document doc = builder.parse(new File(path));

            return returnNodes(doc);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     *
     * @param doc
     * @return
     */
    public ArrayList<Question> returnNodes(Document doc) {
        try {
            ArrayList<Question> lst = new ArrayList<Question>();
            DocumentTraversal docTraversal = (DocumentTraversal) doc;
            NodeIterator nodeIterator = docTraversal.createNodeIterator(doc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);

            Node currentNode = nodeIterator.nextNode();
            while (currentNode != null) {
                if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) currentNode;
                    if (element.getNodeName().equals("question")) {
                        NodeList child = element.getChildNodes();
                        Question ques = null;
                        for (int j = 0; j < child.getLength(); j++) {
                            if (child.item(j).getNodeName().equals("question-content")) {
                                Element userNode = (Element) child.item(j).getParentNode();
                                ques = new Question();
                                ques.setId(userNode.getAttribute("id"));
                                ques.setQuestion(userNode.getElementsByTagName("question-content").item(0).getTextContent());

                                NodeList nodes = userNode.getElementsByTagName("answer");

                                ArrayList<String> ansList = new ArrayList<String>();
                                for (int i = 0; i < nodes.getLength(); i++) {
                                    ansList.add(nodes.item(i).getTextContent());
                                }
                                ques.setAnsList(ansList);
                                lst.add(ques);
                            }
                        }
                    }
                }
                currentNode = nodeIterator.nextNode();
            }

            return lst;
        } catch (Exception ex) {
            Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * 
     * @param doc
     * @param questionId
     * @param path
     */
    public void deleteQuestion(Document doc, String questionId, String realPath) throws Exception{
        String expression= "//questions/question";
        SurveyBiz sbiz = new SurveyBiz();
        try {
            XPathFactory xpFactory = XPathFactory.newInstance();
            XPath xp = xpFactory.newXPath();

            NodeList nodes = (NodeList)xp.evaluate(expression, doc, XPathConstants.NODESET);

            Element elem;
            for (int i= 0; i < nodes.getLength(); i++) {
                elem = (Element)nodes.item(i);
                //JOptionPane.showMessageDialog(null, surveyId+"-"+elem.getAttribute("id"));
                if (elem.getAttribute("id").equals(questionId)) {
                    doc.getDocumentElement().removeChild(elem);
                }
            }

            FileOutputStream fos = new FileOutputStream(new File(realPath));
            sbiz.outputData(doc, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
